package com.itbaizhan.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBConn {
    // MySQL连接URL，指定数据库名为flowerstore，使用SSL连接并设置时区
    private static String url = "jdbc:mysql://localhost:3306/flowerstore?useSSL=false&serverTimezone=UTC";
    private static String username = "root";      // MySQL用户名
    private static String password = "57740251";  // MySQL密码
    private static String jdbc = "com.mysql.cj.jdbc.Driver";  // MySQL JDBC驱动类

    /**
     * 获得数据库的连接
     * @return 数据库连接对象
     */
    public static Connection getConn() {
        Connection conn = null;
        try {
            Class.forName(jdbc);
            conn = DriverManager.getConnection(url, username, password);
            System.out.println("MySQL数据库连接成功");
        } catch (ClassNotFoundException e) {
            System.err.println("MySQL JDBC驱动加载失败: " + e.getMessage());
            e.printStackTrace();
        } catch (SQLException e) {
            System.err.println("数据库连接失败: " + e.getMessage());
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * 关闭数据库的连接
     * @param conn 数据库连接对象
     * @param ps   预编译语句对象
     * @param rs   结果集对象
     */
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        // 关闭资源时遵循从里到外的顺序：ResultSet -> PreparedStatement -> Connection
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
                System.out.println("数据库连接已关闭");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}